package com.application.lucky.adapter;

import android.app.Activity;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.SectionIndexer;

import com.application.lucky.R;
import com.application.lucky.bean.jsonBean.UiBean;
import com.application.lucky.request.nav.UrlManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qunar.im.ui.util.ProfileUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by lixuce on 2018/10/17.
 */

public class FriendsAdapter extends BaseQuickAdapter<UiBean, BaseViewHolder> implements SectionIndexer {


    public FriendsAdapter(int layoutResId) {
        super(layoutResId);
    }

    @Override
    protected void convert(final BaseViewHolder helper, final UiBean bean) {
        int position = helper.getAdapterPosition();
        int section = getSectionForPosition(position - 1);
        //如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现

        if (TextUtils.isEmpty(bean.name)) {
            bean.name = "1";
        }
        ImageView thumb = helper.getView(R.id.iv_item_contact_thumb);
        boolean b = position - 1 == getPositionForSection(section);
//        boolean matches = compile.matcher(bean.name).matches();
        helper.setGone(R.id.tv_item_contact_title, b)
                .setText(R.id.tv_item_contact_title, bean.letters)
                .addOnClickListener(R.id.rl)
                .setText(R.id.tv_item_cantact_name, bean.name);

        ProfileUtils.displayGravatarRoundedCornerByImageSrc((Activity) mContext, UrlManager.getHeadPic(bean.avatarUrl), thumb);
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的char ascii值
     */
    public int getSectionForPosition(int position) {
        return mData.get(position).letters.charAt(0);
    }

    @Override
    public Object[] getSections() {
        return new Object[0];
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        if (mData.size() <= 0) {
            return -1;
        }
        try {
            for (int i = 0; i < getItemCount(); i++) {
                String sortStr = mData.get(i).letters;
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
        } catch (Exception e) {

        }

        return -1;
    }

}
